<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *      [PinTuXiu] (C)2001-2099 ONightjar.com Pintuxiu.com.
 *      This is NOT a freeware, use is subject to license terms
*/
include_once APPPATH.'modules/cloudattach/upyun/upyun.class.php';
class upyun_api{
	private $channel='upyun';
	protected $info;
	protected $client;

	function __construct(){
		$settingapi = load_api('setting');
		$settingkey = 'cloudattach';
		$cloudSetting = $settingapi->getSetting($settingkey);
		$apisetting = $cloudSetting[$this->channel];
		$this->info = array(
				'bucket'=>$apisetting['bucket'],
				'user'=>$apisetting['user'],
				'password'=>$apisetting['password'],
		);;
		$this->client = new UpYun($apisetting['bucket'], $apisetting['user'], $apisetting['password']);
	}

	public function upload($file){
		$absolute_path = $file['absolute'];
		$relative_path = '/'.ltrim($file['relative'],'/');
		if(file_exists($absolute_path)){
			try {
				$fh = fopen($absolute_path, 'rb');
				$rsp = $this->client->writeFile($relative_path, $fh, True);
				fclose($fh);
				return array('success'=>$rsp);
				//var_dump($rsp);
			}catch(Exception $e) {
				return array('success'=>false,'code'=>$e->getCode(),'message'=>$e->getMessage());
			}
		}
		return array('success'=>true);

	}

	public function delete($file){
		$absolute_path = $file['absolute'];
		$relative_path = '/'.ltrim($file['relative'],'/');
		try {
			$rsp = $this->client->delete($relative_path);
			return array('success'=>$rsp);
		}catch(Exception $e) {
			return array('success'=>false,'code'=>$e->getCode(),'message'=>$e->getMessage());
		}
		return array('success'=>true);
	}

	public function download($file){
		$absolute_path = $file['absolute'];
		$relative_path = '/'.ltrim($file['relative'],'/');
		try {
			$fh = fopen($absolute_path, 'w');
			$this->client->readFile($relative_path, $fh);
			fclose($fh);
			return array('success'=>true);
		}catch(Exception $e) {
			return array('success'=>false,'code'=>$e->getCode(),'message'=>$e->getMessage());
		}
		return array('success'=>true);
	}

}
